package com.topfun.utils;

import com.google.gson.JsonObject;
import com.topfun.vo.Menu;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 自定义菜单帮助类
 *
 * @author Administrator
 */
public class MenuUtil {
    private static Logger logger = LoggerFactory.getLogger(MenuUtil.class);

    // 菜单创建（POST）
    public final static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    // 菜单查询（GET）
    public final static String menu_get_url    = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
    // 菜单删除（GET）
    public final static String menu_delete_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

    /**
     * 创建菜单
     *
     * @param menu        菜单实例
     * @param accessToken 凭证
     * @return true成功 false失败
     */
    public static boolean createMenu(Menu menu, String accessToken) {
        boolean result = false;
        String  url    = menu_create_url.replace("ACCESS_TOKEN", accessToken);
        // 将菜单对象转换成json字符串
        String postBody = GsonUtil.toJson(menu);
        // 发起POST请求创建菜单
        OkHttpClient client          = new OkHttpClient();
        MediaType    MEDIA_TYPE_JSON = MediaType.parse("application/json");
        logger.debug(String.format("postBody %s", postBody));
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MEDIA_TYPE_JSON, postBody))
                .build();
        try {
            Response   response   = client.newCall(request).execute();
            String     json       = response.body().string();
            JsonObject jsonObject = GsonUtil.stringToJsonObject(json);
            if (null != jsonObject) {
                int    errorCode = jsonObject.get("errcode").getAsInt();
                String errorMsg  = jsonObject.get("errmsg").getAsString();
                if (0 == errorCode) {
                    result = true;
                } else {
                    result = false;
                    logger.error(String.format("创建菜单失败 errcode:{%s} errmsg:{%s}", errorCode, errorMsg));
                }
            }
        } catch (IOException e) {
            logger.error("创建菜单失败 ");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 查询菜单
     *
     * @param accessToken 凭证
     * @return
     */
    public static String getMenu(String accessToken) {
        String result     = null;
        String requestUrl = menu_get_url.replace("ACCESS_TOKEN", accessToken);
        // 发起GET请求查询菜单
        OkHttpClient client  = new OkHttpClient();
        Request      request = new Request.Builder().url(requestUrl).get().build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            logger.error("查询菜单失败");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除菜单
     *
     * @param accessToken 凭证
     * @return true成功 false失败
     */
    public static boolean deleteMenu(String accessToken) {
        boolean result     = false;
        String  requestUrl = menu_delete_url.replace("ACCESS_TOKEN", accessToken);
        // 发起GET请求删除菜单
        OkHttpClient client  = new OkHttpClient();
        Request      request = new Request.Builder().url(requestUrl).get().build();
        try {
            Response   response   = client.newCall(request).execute();
            String     strJson    = response.body().string();
            JsonObject jsonObject = GsonUtil.stringToJsonObject(strJson);
            if (null != jsonObject) {
                int    errorCode = jsonObject.get("errcode").getAsInt();
                String errorMsg  = jsonObject.get("errmsg").getAsString();
                if (0 == errorCode) {
                    result = true;
                } else {
                    result = false;
                    logger.error(String.format("删除菜单失败 errcode:{%s} errmsg:{%s}", errorCode, errorMsg));
                }
            }
        } catch (IOException e) {
            logger.error("查询菜单失败");
            e.printStackTrace();
        }

        return result;
    }

}
